package com.laoxu.java.thread;

import org.apache.commons.lang3.StringUtils;

/**
 * @Author laoxu
 * @Date 2022/11/22 15:51
 * @Desc 龟兔赛跑的多线程实现
 */
public class TorRabbitRace implements Runnable {
    private String winner;

    // 谁先跑完100步谁赢
    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            // 判断当前线程名称如果为兔子就10的倍数步数停10毫秒，确保乌龟赢
            if(Thread.currentThread().getName().equals("兔子") && i%10==0){
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");
            // 判断是否出现胜者
            if(gameover(i)){
                break;
            }
        }
    }

    boolean gameover(int steps){
        if(!StringUtils.isEmpty(winner)){
            System.out.println("比赛结束！胜者为："+winner);
            return true;
        }
        if(steps>=100){
            winner = Thread.currentThread().getName();
            System.out.println("胜者为："+winner);
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        TorRabbitRace trr = new TorRabbitRace();
        Thread tor = new Thread(trr,"乌龟");
        Thread tr = new Thread(trr,"兔子");
        tor.start();
        tr.start();
    }
}
